<template>
<div>
      <FouDialog
      :title="'添加/修改'"
      :width="'75%'"
      v-model:dialogValue="dialogValue"
    >
    <template #content>
            <el-form :model="form" label-width="150px" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="產品組合名稱" prop="name"><el-input v-model="form.name" /></el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="產品分類" prop="products_type_id">
                <el-select  v-model="form.products_type_id"  size="default" >
                    <el-option v-for="item in producttypeList" :key="item.value" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="產品品牌" prop="brand_id">
               <el-select  v-model="form.brand_id"  size="default" >
                    <el-option v-for="item in brandList" :key="item.value" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>

         <el-col :span="8">
          <el-form-item label="單位" prop="unit_id">
                <el-select  v-model="form.unit_id"  size="default" >
                    <el-option v-for="item in unitList" :key="item.value" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="條形碼" prop="barcode" ><el-input v-model="form.barcode" /></el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="編號" prop="number" type="number"><el-input v-model="form.number" /></el-form-item>
        </el-col> -->

        <el-col :span="8">
          <el-form-item label="價格" prop="price"><el-input v-model="form.price" type="number"/></el-form-item>
        </el-col>
                <el-col :span="8">
          <el-form-item label="摘要" prop="digest"><el-input v-model="form.digest"/></el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="備註" prop="remark"><el-input v-model="form.remark" type="textarea" /></el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="狀態" prop="status">
                <el-select  v-model="form.status"  size="default" >
                    <el-option v-for="item in statusOptions" :key="item.value" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="限时优惠状态" prop="discountstatus">
              <el-switch v-model="form.discountstatus" @change="discountSwitch" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="限時優惠時間" prop="discounttime" v-show="form.discountstatus">
                  <el-date-picker
                    v-model="form.discounttime"
                    type="datetimerange"
                    range-separator="至"
                    format="YYYY/MM/DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    start-placeholder="限時優惠開始時間"
                    end-placeholder="限時優惠結束時間"
                  />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="折扣價"  v-show="form.discountstatus" prop="discountprice"><el-input v-model="form.discountprice" type="number" /></el-form-item>
        </el-col>
        <el-col :span="24" >
         <el-form-item label="添加產品" prop="product_item">
            <el-button  class="button"  color="#F7B32B"   @click="addProductButton" >添加產品</el-button>
            <!-- <div class="flex items-center">
            <div v-for="(value, index) in contact" :key="index" class="flex items-center ml-[10px]"><el-icon><User /></el-icon>{{value.name}}</div>
            </div> -->
          </el-form-item>
        </el-col>
         <el-col :span="15" >
              <ProTable
                :data="form.product_item"
                :column="productcolumn"
                :elProps="{border:true,maxHeight:'400px',
                cellStyle:{
                textAlign:'center',
                  },
                headerCellStyle:{
                  textAlign:'center',
                },
                }"
                :page="[]"
                :rowControl="[]"
                :disabled="[]"
                :controlWidth="[]"
              >
                    <template #default="{ row, propname }">
                      <div v-if="propname === 'price' || propname === 'num'">
                        <el-input v-model="row[propname]" type="number"></el-input>
                      </div>
                    </template>
                    <template #search_operate>
                        <el-table-column   min-width="200px" label="操作" >
                          <template #default="scope">
                              <el-popconfirm
                                  confirm-button-text="確認"
                                  cancel-button-text="NO"
                                  title="確認刪除該數據?"
                                   @confirm="confirmEvent"
                                >
                                  <template #reference>
                                <el-button  color="#081F42"  @click="deleteProduct(scope.$index, scope.row)" >刪除</el-button >
                                </template>
                              </el-popconfirm>
                          </template>
                        </el-table-column>
                  </template>
              </ProTable>
         </el-col>

      </el-row>
    </el-form>
    </template>
      <template #footer>
                       <div class="flex justify-end mt-10 w-[100%]" >
            <el-button @click="dialogValue = false">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef,buttonType)" color="#081F42"
              >確定</el-button
            >
           </div>
      </template>
      </FouDialog>
  <addProductDia ref="productDialog" @update="ProductDiaClick"></addProductDia>

</div>
</template>

<script setup>
import { ref  ,reactive, watch } from 'vue' 
import {message,messageBox,loading,closeLoading} from '@/common/function.js'
import {addProductgroup,updateProductgroup } from "@/http/index.js";
import addProductDia from './productDialog.vue'
 const productDialog = ref('')
const addProductButton = async()=>{
  productDialog.value.productDialog = true
  await productDialog.value.tableList()
}
const productcolumn = {
    number: "產品編號",
    name: "產品名稱",
    price:'價格',
    num:'數量'
}

// const form.product_item = ref([])
const ProductDiaClick = (e)=>{
  console.log(e);
  // let product_item = form.product_item.map(e=>({
  //   id:e.id,
  //   name:e.name,
  //   number:e.number,
  //   num:e.num,
  //   price:e.price,
  // }))
  // console.log(product_item);
  form.product_item = [...form.product_item,...e]
  form.product_item.map(e=>e.num = 1)
  console.log(form.product_item);
}
const rowProduct = ref({})
const deleteProduct = (index,row)=>{
      console.log(index,row);
      rowProduct.value = row
      // form.product_item.value  = form.product_item.value.filter(item => item.id != row.id)
}
const confirmEvent = () => {
   form.product_item  = form.product_item.filter(item => item.id != rowProduct.value.id)
}

const dialogValue = ref(false)
const form = reactive({
    name: "",
    products_type_id: "",//產品分類
    brand_id:'',         //產品品牌
    unit_id:'',          //單位
    barcode: "",
    price: "",
    digest:'',
    remark:'',
    status: "",
    product_item:[],
    discountstatus:false,
    // discounttime:'',
    // discountprice:'',
});

const  rules = reactive({
        name:{required:true,message:'请输入產品名稱',trigger: ['blur', 'change']},
        products_type_id:{required:true,message:'请選擇產品分類',trigger: ['blur', 'change']},
        brand_id:{required:true, message:'请選擇品牌',trigger: ['blur', 'change']},
        unit_id:{required:true,message:'请選擇單位',trigger: ['blur', 'change']},
        barcode:{required:true,message:'请輸入產品條形碼',trigger: ['blur', 'change']},
        price:{required:true,message:'请輸入產品價格',trigger: ['blur', 'change']},
        status:{required:true,message:'请選擇產品狀態',trigger: ['blur', 'change']},
        product_item:{required:true,message:'请選擇產品',trigger: ['blur', 'change']},
    })

const statusOptions = [
  {
    id:1,
    name: '發售中',
  },{
    id: -1,
    name: '停售',
  }
]
const ruleFormRef = ref('')
const buttonType = ref('')
const confirm = (formEl,type)=>{
  if (!formEl) return;
      formEl.validate(async (e)=>{
        if (e) {
            let params = JSON.parse(JSON.stringify(form));
            if (params.product_item) {
              params.product_item = JSON.stringify(params.product_item)
            }
            if (params.discounttime ) {
            params.starttime = params.discounttime[0]
            params.endtime = params.discounttime[1]
            }
            delete params.discounttime
            if (params.discountstatus) {
              params.discountstatus = 1
            }else{ params.discountstatus = -1}
            if (type == 'add') {
             await addTableList(params)
            }else{
             await updateTableList(params)
            }
            dialogValue.value = false
        }
    })
}
// // 修改產品
const updateTableList = async (e) => {
  const data = await updateProductgroup(e);
  if (data.code == 200) {
     emit('addConfirm')
    message('修改產品組合成功')
  }
};
// 添加產品
const addTableList = async (e) => {
  console.log(e);
  const data = await addProductgroup(e);
  console.log(data);
  if (data.code == 200) {
     emit('addConfirm')
    message('添加產品組合成功')
  }
};
const props = defineProps({
    echo:Object,
    producttypeList:Object,//產品分類
    brandList:Object,//產品品牌
    supplierList:Object, //供應商
    unitList:Object,//單位
})
Object.assign(form,props.echo)
watch(()=>props.echo,(newval)=>{
Object.assign(form,newval)
})
const emit = defineEmits(['addConfirm','addCancal'])

const discountSwitch = (e)=>{
  if (e) {
        rules.discounttime =  {required:true, message:'请選擇限時優惠開始-結束時間',trigger: ['blur', 'change']}     
        rules.discountprice =  {required:true, message:'请輸入限時優惠價格',trigger: ['blur', 'change']}     
  }else{
        delete form.discounttime
        delete form.discountprice

        delete rules.discounttime
        delete rules.discountprice
  }
}
const inventory = (e)=>{
  if (e) {
    rules.safety= {required:true, message:'请輸入產品安全量',trigger: ['blur', 'change']}
    form.safety = 1
  }else{
    delete rules.safety,
    delete form.safety
  }
}

defineExpose({
    dialogValue,buttonType
})
</script>

<style lang='less'  scoped>
.button{
  color: #fff;
}
</style>